package com.kgc.scd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kgc.scd.bean.ShopUser;
import com.kgc.scd.mapper.ShopUserMapper;
import com.kgc.scd.service.ShopUserService;
import com.kgc.scd.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

/**
 * Created On : 2022/11/14.
 * <p>
 * Author : 刘慧枫
 * <p>
 * Description: 用户登录接口实现类
 */
@Slf4j
@Service
public class ShopUserServiceImpl implements ShopUserService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SnowUtil snowUtil;

    @Autowired(required = false)
    private ShopUserMapper shopUserMapper;

    @Override
    public String userRegister(String userName, String userPwd, String userPhone, String userNickName) {

        //查询手机号是否存在
        QueryWrapper<ShopUser> shopUserQueryWrapper1 = new QueryWrapper<>();
//        shopUserQueryWrapper1.like("mobile", EncodeUtils.hidePhoneNo(userPhone));
        shopUserQueryWrapper1.like("mobile",userPhone);
        if (shopUserMapper.selectOne(shopUserQueryWrapper1) != null){
            return "该号码已注册！";
        }

        //查询账号是否存在
        QueryWrapper<ShopUser> shopUserQueryWrapper2 = new QueryWrapper<>();
        shopUserQueryWrapper2.like("username", userName);
        if (shopUserMapper.selectOne(shopUserQueryWrapper2) != null){
            return "该账号已存在！";
        }

        //查询昵称是否存在
        QueryWrapper<ShopUser> shopUserQueryWrapper3 = new QueryWrapper<>();
        shopUserQueryWrapper3.like("nickname", userNickName);
        if (shopUserMapper.selectOne(shopUserQueryWrapper3) != null){
            return "该昵称已存在！";
        }

        ShopUser shopUser = new ShopUser();
        shopUser.setId(snowUtil.snowId());
        shopUser.setUsername(userName);
        shopUser.setPassword(EncodeUtils.testDigest(userPwd));
        //手机号加密
//        shopUser.setMobile(EncodeUtils.hidePhoneNo(userPhone));
        shopUser.setMobile(userPhone);
        shopUser.setNickname(userNickName);
        //注册时间
        shopUser.setRegisterTime(new Date());
        try {
            //注册时ip
            shopUser.setRegisterIp(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        //注册账号
        shopUserMapper.insert(shopUser);

        return "账号注册成功！";
    }

    @Override
    public String userRegisterByWeChat(String openId, String nickname, Integer sex) {

        //创建user对象，注册用户
        ShopUser shopUser = new ShopUser();
        shopUser.setId(snowUtil.snowId());
        shopUser.setWeixinOpenid(openId);
        shopUser.setNickname(nickname);
        shopUser.setGender(sex);
        shopUser.setRegisterTime(new Date());
        try {
            //注册时ip
            shopUser.setRegisterIp(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        shopUserMapper.insert(shopUser);

        //UUID生成令牌
        String userToken = EncodeUtils.testDigest(shopUser.getId());

        //将查询出的用户详情，直接以token值作为key，存入到redis缓存中，并增加时效（有过期时间，比如30分钟）
        redisUtils.set(userToken,shopUser);

        //返回有效的token令牌。此令牌代表登录成功的用户
        return userToken;
    }

    @Override
    public String userLoginByWeChat(String openId, String nickname, Integer sex) {
        //查询昵称是否存在
        QueryWrapper<ShopUser> shopUserQueryWrapper = new QueryWrapper<>();
        shopUserQueryWrapper.like("weixin_openid", openId);
        if (shopUserMapper.selectOne(shopUserQueryWrapper) == null){
            userRegisterByWeChat(openId,nickname,sex);
        }

        //查询的用户详情
        ShopUser shopUser = shopUserMapper.selectOne(shopUserQueryWrapper);
        //更新登录时间
        shopUser.setLastLoginTime(new Date());
        //更新登录ip
        try {
            //注册时ip
            shopUser.setLastLoginIp(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        shopUserMapper.updateById(shopUser);


        //UUID生成令牌
        String userToken = EncodeUtils.testDigest(shopUser.getId());
        //将查询出的用户详情，直接以token值作为key，存入到redis缓存中，并增加时效（有过期时间，比如30分钟）
        redisUtils.set(userToken,shopUser);

        //返回有效的token令牌。此令牌代表登录成功的用户
        return userToken;

    }

    @Override
    public String bindUserPhone(ShopUser shopUser, String userPhone) {

//        //根据token获取用户信息
//        Object userObj =redisUtils.get(userToken);
//        ShopUser shopUser = JSON.parseObject(userObj.toString(),ShopUser.class);

        //查询手机号是否存在
        QueryWrapper<ShopUser> shopUserQueryWrapper = new QueryWrapper<>();
//        shopUserQueryWrapper.like("mobile", EncodeUtils.hidePhoneNo(userPhone));
        shopUserQueryWrapper.like("mobile",userPhone);
        if (shopUserMapper.selectOne(shopUserQueryWrapper) != null){

            shopUser.setUsername(shopUserMapper.selectOne(shopUserQueryWrapper).getUsername());
            shopUser.setPassword(shopUserMapper.selectOne(shopUserQueryWrapper).getPassword());
            shopUser.setMobile(shopUserMapper.selectOne(shopUserQueryWrapper).getMobile());
            shopUser.setRegisterTime(shopUserMapper.selectOne(shopUserQueryWrapper).getRegisterTime());
            shopUser.setRegisterIp(shopUserMapper.selectOne(shopUserQueryWrapper).getRegisterIp());
            //更新微信账号
            shopUserMapper.updateById(shopUser);

            //绑定微信账号到手机号
            shopUserMapper.update(shopUser,shopUserQueryWrapper);

            //删除微信登录账号
            shopUserMapper.deleteById(shopUser.getId());
            //删除微信登录令牌
            redisUtils.del(EncodeUtils.testDigest(shopUser.getId()));

            //UUID生成令牌
            String userToken = EncodeUtils.testDigest(shopUserMapper.selectOne(shopUserQueryWrapper).getId());
            redisUtils.set(userToken,shopUserMapper.selectOne(shopUserQueryWrapper));

            return "手机号绑定成功！";
        }

        //判断是否绑定手机
        if (StringUtils.isNotBlank(shopUser.getMobile())){
            return "已经绑定手机号，直接登录！";
        }

        //绑定手机号
        shopUser.setMobile(userPhone);

        //UUID生成令牌
        String userToken = EncodeUtils.testDigest(shopUser.getId());
        redisUtils.set(userToken,shopUser);
        shopUserMapper.updateById(shopUser);

        return "手机号绑定成功！";
    }

    @Override
    public String userLogin(String userName, String userPwd) {

        //查询用户名
        QueryWrapper<ShopUser> shopUserQueryWrapper = new QueryWrapper<>();
        shopUserQueryWrapper.like("username", userName);
        if (shopUserMapper.selectOne(shopUserQueryWrapper) == null){
            return "用户名不存在，请重新输入！";
        }

        //查询的用户详情
        ShopUser shopUser = shopUserMapper.selectOne(shopUserQueryWrapper);

        //更新登录时间
        shopUser.setLastLoginTime(new Date());
        //更新登录ip
        try {
            //注册时ip
            shopUser.setLastLoginIp(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        shopUserMapper.updateById(shopUser);

        if (!shopUser.getPassword().equals(EncodeUtils.testDigest(userPwd))){
            return "密码错误，请重新输入!";
        }

        if (shopUser.getUsername().equals(userName) && shopUser.getPassword().equals(EncodeUtils.testDigest(userPwd))){

            //UUID生成令牌
//            String userToken = UUID.randomUUID().toString().replace("-", "_");
            String userToken = EncodeUtils.testDigest(shopUser.getId());

            //将查询出的用户详情，直接以token值作为key，存入到redis缓存中，并增加时效（有过期时间，比如30分钟）
            redisUtils.set(userToken,shopUser);
//            redisUtils.set("sms:phone:" + userPhone,shopUser.getId());

            //返回有效的token令牌。此令牌代表登录成功的用户
            return userToken;

        }
        //鉴权失败，返回null
        return null;
    }

    @Override
    public String userLoginByPhone(String userPhone, String verifyCode) {

        //查询手机号
        QueryWrapper<ShopUser> shopUserQueryWrapper = new QueryWrapper<>();
//        shopUserQueryWrapper.like("mobile", EncodeUtils.hidePhoneNo(userPhone));
        shopUserQueryWrapper.like("mobile",userPhone);

        if (shopUserMapper.selectOne(shopUserQueryWrapper) == null){
            return "手机号不存在,请重新输入！";
        }

        //查询的用户详情
        ShopUser shopUser = shopUserMapper.selectOne(shopUserQueryWrapper);

        //更新登录时间
        shopUser.setLastLoginTime(new Date());
        //更新登录ip
        try {
            //注册时ip
            shopUser.setLastLoginIp(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        shopUserMapper.updateById(shopUser);

//        if (shopUser.getMobile().equals(EncodeUtils.hidePhoneNo(userPhone)) && redisUtils.get("sms:phone:" + userPhone).equals(verifyCode)){
        if (shopUser.getMobile().equals(userPhone) && redisUtils.get("sms:phone:" + userPhone).equals(verifyCode)){

            //UUID生成令牌
//            String userToken = UUID.randomUUID().toString().replace("-", "_");
            String userToken = EncodeUtils.testDigest(shopUser.getId());

            //将查询出的用户详情，直接以token值作为key，存入到redis缓存中，并增加时效（有过期时间，比如30分钟）
            redisUtils.set(userToken,shopUser);

            //返回有效的token令牌。此令牌代表登录成功的用户
            return userToken;

        }
        //鉴权失败，返回null
        return null;
    }
}
